import axios from "axios";
import type { AxiosRequestConfig } from "axios";
import NProgress from "nprogress"; // 进度条
import Qs from "qs";

NProgress.configure({ easing: "ease", showSpinner: false });

import Request from "./request";

const req = new Request({
    timeout: 120 * 1000,
    baseURL: import.meta.env.VITE_BASE_URL,
    headers: {
        "Content-Type": "application/json;charset=UTF-8",
    },
});
declare type requestData = object | null | undefined;

const ajax = {
    get(url: string, data?: requestData, options: AxiosRequestConfig = {}) {
        return req.request({
            method: "get",
            url,
            params: data,
            ...options,
        });
    },
    post(url: string, data?: requestData, options: AxiosRequestConfig = {}) {
        return req.request({
            method: "post",
            url,
            data,
            ...options,
        });
    },
    postForm(url: string, data?: requestData, options: AxiosRequestConfig = {}) {
        options = Object.assign(options, { headers: { "Content-Type": "application/x-www-form-urlencoded" } });

        return req.request({
            method: "post",
            url,
            data: data ? Qs.stringify(data) : "",
            ...options,
        });
    },
    put(url: string, data?: requestData, options: AxiosRequestConfig = {}) {
        return req.request({
            method: "put",
            url,
            data,
            ...options,
        });
    },
    delete(url: string, data?: requestData, options: AxiosRequestConfig = {}) {
        return req.request({
            method: "delete",
            url,
            data,
            ...options,
        });
    },
    all: axios.all,
    spread: axios.spread,
};

export default ajax;
